<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Model\GoodsSpecRel;
use App\Validate\Admin\Goods;
use Illuminate\Http\Request;
use App\Model\GoodsSpu;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
 * 商品管理
 */
class GoodsController extends Controller
{

    /**
     * 定义模型
     */
    protected $model;

    /**
     * 定义验证
     */
    protected $validate;

    /**
     * 初始化控制器
     */
    public function __construct()
    {
        $this->model = (new GoodsSpu());
        $this->validate = (new Goods());
    }

    /**
     * 商品映射
     */
    public function goods_mapping()
    {
        // 规格类型
        $spec_type = $this->model->getSpecTypeList();
        // 状态
        $status = $this->model->getStatusList();
        $this->success(['spec_type' => $spec_type, 'status' => $status]);
    }

    /**
     * 商品列表
     */
    public function goods_list(Request $request)
    {
        // 获取参数
        $params = $request->all();
        // 设置对象
        $model = $this->model;
        // id
        if (isset($params['goods_id']) && $params['goods_id']) {
            $model = $model->where('id', $params['goods_id']);
        }
        // 分类
        if (isset($params['cate_id']) && $params['cate_id']) {
            $model = $model->where('cate_id', $params['cate_id']);
        }
        // 品牌
        if (isset($params['brand_id']) && $params['brand_id']) {
            $model = $model->where('brand_id', $params['brand_id']);
        }
        // 商品编码
        if (isset($params['goods_sn']) && $params['goods_sn']) {
            $model = $model->where('goods_sn', 'like', '%' . $params['goods_sn'] . '%');
        }
        // 标题
        if (isset($params['title']) && $params['title']) {
            $model = $model->where('title', 'like', '%' . $params['title'] . '%');
        }
        // 规格类型
        if (isset($params['spec_type']) && $params['spec_type']) {
            $model = $model->where('spec_type', $params['spec_type']);
        }
        // 状态
        if (isset($params['status']) && $params['status']) {
            $model = $model->where('status', $params['status']);
        }
        // 创建时间
        if (!empty($params['start_createtime']) && !empty($params['end_createtime'])) {
            $model = $model->whereBetween('createtime', [$params['start_createtime'], $params['end_createtime']]);
        }
        // 修改时间
        if (!empty($params['start_updatetime']) && !empty($params['end_updatetime'])) {
            $model = $model->whereBetween('updatetime', [$params['start_updatetime'], $params['end_updatetime']]);
        }
        // 获取条数
        $pageSize = isset($params['pageSize']) && $params['pageSize'] ? $params['pageSize'] : 10;
        $total = $model->count();
        $list = $model
            ->orderBy('id', 'desc')
            ->take($pageSize)
            ->get(['id as goods_id', 'cate_id', 'brand_id', 'goods_sn', 'sku_sn', 'bar_code', 'title', 'spec_type',
                'supply_price', 'line_price', 'image', 'thumb_image', 'stock', 'status', 'createtime', 'updatetime'])
            ->toArray();
        $goodsCateArr = $this->goods_category(1);
        $goodsBrandArr = $this->goods_brand(1);
        foreach ($list as &$val) {
            if (isset($goodsCateArr[$val['cate_id']])) {
                $val['cate_text'] = $goodsCateArr[$val['cate_id']];
            }
            if (isset($goodsBrandArr[$val['brand_id']])) {
                $val['brand_text'] = $goodsBrandArr[$val['brand_id']];
            }
            $val['image'] = replace_imgs_url($val['image']);
            $val['thumb_image'] = replace_imgs_url($val['thumb_image']);
        }
        $this->success(['total_count' => $total, 'total_page' => ceil($total / $pageSize), 'list' => $list]);
    }

    /**
     * 添加商品
     */
    public function add_goods(Request $request)
    {
        // 获取参数
        $only = ['cate_id', 'brand_id', 'goods_sn', 'sku_sn', 'bar_code', 'title', 'subtitle', 'spec_type',
            'supply_price', 'line_price', 'image', 'thumb_image', 'images', 'details', 'weight', 'stock', 'status'];
        $params = $request->only($only);
        $spec_many_params = $request->input('spec_many');
        if ($params) {
            // 规则验证
            if (!$this->validate->check($params, [], [], 'add_goods')) {
                $this->error($this->validate->getError());
            }
            DB::beginTransaction();
            try {
                foreach ($params as $key => $val) {
                    if (isset($val)) {
                        $this->model->$key = $val;
                    }
                }
                $result = $this->model->save();
                if ($result !== false) {
                    //成功之后 存储商品规格
                    $this->model->addGoodsSku($params, $spec_many_params);
                    DB::commit();
                } else {
                    throw new \Exception('操作失败');
                }
            } catch (\Exception $exception) {
                DB::rollBack();
                $this->error($exception->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error('未插入任何行');
            }
        }
        $this->error('参数不能为空');
    }

    /**
     * 商品详情
     */
    public function goods_details(Request $request)
    {
        // 获取参数
        $ids = $request->input('goods_id');
        $row = $this->model->with(['goodsSpecRel', 'sku', 'goodsSpecRel.spec'])->where('id', $ids)->first();
        if (!$row) {
            $this->error('记录未找到');
        }
        $row['image_url'] = replace_imgs_url($row['image']);
        $row['images_url'] = replace_imgs_arr_url(explode(',', $row['image']));
        $row['specData'] = 'null';
        if ($row['spec_type'] == 2) {
            $row['specData'] = $this->model->getManySpecData($row['goodsSpecRel'], $row['sku']);
        }
        $this->success($row);
    }

    /**
     * 编辑商品
     */
    public function edit_goods(Request $request)
    {
        // 获取参数
        $only = ['goods_id', 'cate_id', 'brand_id', 'goods_sn', 'sku_sn', 'bar_code', 'title', 'subtitle', 'spec_type',
            'supply_price', 'line_price', 'image', 'thumb_image', 'images', 'details', 'weight', 'stock', 'status'];
        $params = $request->only($only);
        $spec_many_params = $request->input('spec_many');
        if ($params) {
            // 规则验证
            if (!$this->validate->check($params, [], [], 'edit_goods')) {
                $this->error($this->validate->getError());
            }
            DB::beginTransaction();
            try {
                $goodsSpu = $this->model::find($params['goods_id']);
                unset($params['goods_id']);
                foreach ($params as $key => $val) {
                    if (isset($val)) {
                        $goodsSpu->$key = $val;
                    }
                }
                $result = $goodsSpu->save();
                if ($result !== false) {
                    //成功之后 存储商品规格
                    $goodsSpu->addGoodsSku($params, $spec_many_params, true);
                    Db::commit();
                } else {
                    throw new \Exception('操作失败');
                }
            } catch (\Exception $exception) {
                DB::rollBack();
                $this->error($exception->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error('未更新任何行');
            }
        }
        $this->error('参数不能为空');
    }

    /**
     * 删除商品
     */
    public function del_goods(Request $request)
    {
        // 获取参数
        $ids = $request->input('goods_id');
        if ($ids) {
            $count = 0;
            DB::beginTransaction();
            try {
                $list = $this->model::find(explode(',', $ids));
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (\Exception $exception) {
                DB::rollBack();
                $this->error($exception->getMessage());
            }
            if ($count) {
                $this->success($count);
            } else {
                $this->error(__('未删除任何行'));
            }
        }
        $this->error('参数不能为空');
    }

    /**
     * 批量商品
     */
    public function multi_goods(Request $request)
    {
        // 获取参数
        $ids = $request->input('goods_id');
        $field_key = $request->input('field_key');
        $field_val = $request->input('field_val');
        if ($ids && $field_key && $field_val) {
            if (Schema::hasColumn('goods_spu', $field_key)) {
                $count = 0;
                DB::beginTransaction();
                try {
                    $list = $this->model::find(explode(',', $ids));
                    foreach ($list as $k => $v) {
                        $v->$field_key = $field_val;
                        $count += $v->save();
                    }
                    Db::commit();
                } catch (\Exception $exception) {
                    DB::rollBack();
                    $this->error($exception->getMessage());
                }
                if ($count) {
                    $this->success($count);
                } else {
                    $this->error(__('未更新任何行'));
                }
            } else {
                $this->error('字段不存在');
            }
        }
        $this->error('参数不能为空');
    }

    /**
     * 商品分类
     */
    public function goods_category($is_inside = 0)
    {
        $result = push_control('GOODS_CATEGORY_QUERY');
        if ($result['code'] == 0) {
            $this->error($result['msg']);
        }
        $arr = [];
        foreach ($result['data']['list'] as $list) {
            foreach ($list as $item) {
                array_push($arr, $item);
            }
        }
        if ($is_inside == 1) {
            return array_column($arr, 'cate_name', 'id');
        } else {
            $arr = recursion($arr);
            $this->success($arr);
        }
    }

    /**
     * 商品品牌
     */
    public function goods_brand($is_inside = 0)
    {
        $content = [
            'page' => 1,//当前页
            'pageSize' => 1,//总页数
        ];
        $result = push_control('GOODS_BRAND_QUERY', $content);
        if ($result['code'] == 0) {
            $this->error($result['msg']);
        }
        // 设置每页获取条数
        $pageSize = 500;
        // 获取总页数
        $totalPage = ceil($result['data']['total'] / $pageSize);
        $arr = [];
        for ($i = 1; $i <= $totalPage; $i++) {
            $content['page'] = $i;
            $content['pageSize'] = $pageSize;
            $result = push_control('GOODS_BRAND_QUERY', $content);
            if ($result['code'] == 0) {
                $this->error($result['msg']);
            }
            $list = $result['data']['list'];
            foreach ($list as $item) {
                $arr[$item['id']] = $item['name'];
            }
        }
        if ($is_inside == 1) {
            return $arr;
        } else {
            $this->success($arr);
        }
    }
}
